package abq2.jic.jic.plugin.other.other.mob.mob;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.lang.Lang;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.message.api.DingdingMessageInfo;
import kd.bos.message.api.DingdingMsgOperateType;
import kd.bos.message.api.DingdingTodoInfo;
import kd.bos.message.api.DingdingTodoOperateType;
import kd.bos.servicehelper.message.MessageServiceHelper;
import kd.bos.workflow.engine.WfConfigurationUtil;
import kd.bos.workflow.engine.WfMultiLangUtils;
import kd.bos.workflow.engine.WfUtils;
import kd.bos.workflow.engine.msg.AbstractMessageServiceHandler;
import kd.bos.workflow.engine.msg.MessageServiceUtil;
import kd.bos.workflow.engine.msg.ctx.MessageContext;
import kd.bos.workflow.engine.msg.handler.DingdingServiceHandler;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import kd.bos.workflow.engine.msg.info.ToDoInfo;
import kd.bos.workflow.engine.msg.model.yzj.MessageUser;
import kd.bos.workflow.engine.msg.util.MessageUtils;
import kd.bos.workflow.engine.msg.util.dingding.DingdingCommonUtil;
import kd.bos.workflow.engine.msg.util.yzj.YunzhijiaToDoUtil;
import kd.bos.workflow.exception.WFErrorCode;
import kd.bos.workflow.exception.WFMessageServiceException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DingdingBookServiceHandler extends AbstractMessageServiceHandler {
    private static Log logger = LogFactory.getLog(DingdingServiceHandler.class);
    private static final String TYPE = "dingding";
    private static final int DINGDINGTYPEID = 2;
    private static final String EXCEPTIONDESCRIPTION = "take DingdingHandler has exception ";


    public void createToDo(MessageContext ctx, ToDoInfo info) {
        if (WfConfigurationUtil.isEnabled("dingding")) {
            try {
                MessageServiceUtil.updateToDoMsgContent(this.config, info);
                List<ToDoInfo> toDoInfos = YunzhijiaToDoUtil.rebuildToDoInfo(info);
                Iterator var4 = toDoInfos.iterator();

                label95:
                while(var4.hasNext()) {
                    ToDoInfo toDoInfo = (ToDoInfo)var4.next();
                    JSONArray dingTaskList = DingdingCommonUtil.getdingTodoInfo(toDoInfo);
                    if (!dingTaskList.isEmpty()) {
                        return;
                    }

                    Long startUserId = ctx.getStartUserId();
                    List<Long> startUserIds = new ArrayList();
                    startUserIds.add(startUserId);
                    List<MessageUser> startUserList = DingdingCommonUtil.getOpenIds(startUserIds, 2);
                    if (startUserList != null && startUserList.size() != 0) {
                        String startUserOpenId = ((MessageUser)startUserList.get(0)).getOpenId();
                        logger.info("DingdingServiceHandler--create todo info:" + toDoInfo);
                        List<Long> userIds = toDoInfo.getUserIds();
                        List<MessageUser> users = DingdingCommonUtil.getOpenIds(userIds, 2);
                        String lang = Lang.get().toString();
                        if (userIds != null && !userIds.isEmpty()) {
                            lang = WfMultiLangUtils.getUserDefaultLang((Long)userIds.get(0));
                        }

                        JSONObject tplMap = DingdingCommonUtil.getDingTpl(ctx.getEntityNumber(), ctx.getEntityName());
                        if (tplMap == null) {
                            throw new WFMessageServiceException(ResManager.loadKDString("应用id没有配置。", "DingdingServiceHandler_4", "bos-wf-engine", new Object[0]));
                        }

                        Iterator var15 = users.iterator();

                        Map resultMap;
                        label88:
                        do {
                            while(var15.hasNext()) {
                                MessageUser messageUser = (MessageUser)var15.next();
                                String userId = messageUser.getOpenId();
                                if (userId != null && !StringUtils.isBlank(userId)) {
                                    DingdingTodoInfo dingdingTodoInfo = new DingdingTodoInfo();
                                    String title = DingdingCommonUtil.wrapContent(lang, toDoInfo.getTitle());
                                    if (!WfUtils.isEmpty(title)) {
                                        dingdingTodoInfo.setTitle(title);
                                    }

                                    String content = DingdingCommonUtil.wrapContent(lang, toDoInfo.getContent());
                                    if (!WfUtils.isEmpty(content)) {
                                        dingdingTodoInfo.setContent(content);
                                    }

                                    dingdingTodoInfo.setOriginatorUserId(startUserOpenId);
                                    dingdingTodoInfo.setUserId(userId);
                                    dingdingTodoInfo.setTodoUrl(toDoInfo.getUrl());
                                    dingdingTodoInfo.setTodoType(DingdingTodoOperateType.CREATE.getNumber());
                                    boolean isHasTpl = tplMap.getBoolean("ishastpl");
                                    if (isHasTpl) {
                                        dingdingTodoInfo.setHasDingTpl(isHasTpl);
                                        dingdingTodoInfo.setTplProcessCode(tplMap.getString("tplid"));
                                        dingdingTodoInfo.setTplName(tplMap.getString("tplname"));
                                        dingdingTodoInfo.setTplDescription(tplMap.getString("tpldescription"));
                                    } else {
                                        if (StringUtils.isNotBlank(tplMap.getString("tplcode"))) {
                                            dingdingTodoInfo.setTplProcessCode(tplMap.getString("tplcode"));
                                        }

                                        dingdingTodoInfo.setHasDingTpl(isHasTpl);
                                        dingdingTodoInfo.setTplName(ctx.getEntityName());
                                        dingdingTodoInfo.setTplDescription(ctx.getEntityName() + ResManager.loadKDString("审批模板", "DingdingServiceHandler_1", "bos-wf-engine", new Object[0]));
                                    }

                                    String dingProcessInstanceId = DingdingCommonUtil.getDingProcessInstance(ctx.getProcessInstanceId());
                                    if (StringUtils.isNotBlank(dingProcessInstanceId)) {
                                        dingdingTodoInfo.setProcessInstanceId(dingProcessInstanceId);
                                    } else {
                                        String instanceUrl = MessageServiceUtil.buildWebPageUrlForMyInitiation(ctx.getProcessInstanceId());
                                        dingdingTodoInfo.setInstanceUrl(instanceUrl);
                                    }

                                    resultMap = MessageServiceHelper.dingdingTodo(dingdingTodoInfo);
                                    if (!isHasTpl) {
                                        DingdingCommonUtil.saveDingTpl(ctx, dingdingTodoInfo, resultMap);
                                    }

                                    DingdingCommonUtil.saveDingTodo(ctx.getProcessInstanceId(), toDoInfo.getTaskId(), messageUser.getUserId(), dingdingTodoInfo, resultMap);
                                    continue label88;
                                }

                                logger.info("createToDo--userId:" + userId + " openId is null");
                            }

                            logger.info("DingdingServiceHandler--createToDo success");
                            continue label95;
                        } while(resultMap != null && resultMap.get("code") != null && resultMap.get("code").equals("0"));

                        throw new WFMessageServiceException((Throwable)null, WFErrorCode.dingdingMsgError(), new Object[]{"createDingTodoError:" + resultMap});
                    }

                    logger.info("流程发起人openID为空");
                    return;
                }

            } catch (Exception var24) {
                logger.info("DingdingServiceHandler--CreateTodoFail:" + var24.getMessage());
                throw new WFMessageServiceException(var24, WFErrorCode.dingdingMsgError(), new Object[]{var24.getMessage()});
            }
        }
    }

    public void dealToDo(MessageContext ctx, ToDoInfo info) {
        if (WfConfigurationUtil.isEnabled("dingding")) {
            try {
                logger.info("DingdingServiceHandler--deal todo info:" + info);
                JSONArray dingTaskList = DingdingCommonUtil.getdingTodoInfo(info);
                if (dingTaskList.isEmpty()) {
                    logger.info("DingdingServiceHandler--dealToDo--钉钉任务task和实例ID为空 ");
                } else {
                    List<String> successTaskIds = new ArrayList(dingTaskList.size());

                    for(int i = 0; i < dingTaskList.size(); ++i) {
                        Long dingTaskId = dingTaskList.getJSONObject(i).getLong("taskid");
                        String processInstanceId = dingTaskList.getJSONObject(i).getString("processinstanceid");
                        DingdingTodoInfo todoInfo = new DingdingTodoInfo();
                        todoInfo.setProcessInstanceId(processInstanceId);
                        todoInfo.setTaskId(dingTaskId);
                        todoInfo.setTodoType(DingdingTodoOperateType.DEAL.getNumber());
                        Map<String, Object> resultMap = MessageServiceHelper.dingdingTodo(todoInfo);
                        if (resultMap == null || resultMap.get("code") == null || !resultMap.get("code").equals("0")) {
                            throw new WFMessageServiceException((Throwable)null, WFErrorCode.dingdingMsgError(), new Object[]{"take DingdingHandler has exception " + resultMap});
                        }

                        successTaskIds.add(String.valueOf(dingTaskId));
                    }

                    DingdingCommonUtil.updateDingTodo(successTaskIds);
                    logger.info("DingdingServiceHandler--dealToDo success");
                }
            } catch (Exception var10) {
                logger.info("DingdingServiceHandler--deleteTodoFail:" + var10.getMessage());
                throw new WFMessageServiceException(var10, WFErrorCode.dingdingMsgError(), new Object[]{var10.getMessage()});
            }
        }
    }

    public void deleteToDo(MessageContext ctx, ToDoInfo info) {
        if (WfConfigurationUtil.isEnabled("dingding")) {
            try {
                logger.info("DingdingServiceHandler-- delete todo info:" + info);
                JSONArray dingTaskList = DingdingCommonUtil.getdingTodoInfo(info);
                if (dingTaskList.isEmpty()) {
                    logger.info("DingdingServiceHandler--dealToDo--钉钉任务task和实例ID为空 ");
                } else {
                    List<String> successTaskIds = new ArrayList(dingTaskList.size());

                    for(int i = 0; i < dingTaskList.size(); ++i) {
                        Long dingTaskId = dingTaskList.getJSONObject(i).getLong("taskid");
                        String processInstanceId = dingTaskList.getJSONObject(i).getString("processinstanceid");
                        DingdingTodoInfo todoInfo = new DingdingTodoInfo();
                        todoInfo.setProcessInstanceId(processInstanceId);
                        todoInfo.setTaskId(dingTaskId);
                        todoInfo.setTodoType(DingdingTodoOperateType.DELETE.getNumber());
                        Map<String, Object> resultMap = MessageServiceHelper.dingdingTodo(todoInfo);
                        if (resultMap == null || resultMap.get("code") == null || !resultMap.get("code").equals("0")) {
                            throw new WFMessageServiceException((Throwable)null, WFErrorCode.dingdingMsgError(), new Object[]{"take DingdingHandler has exception " + resultMap});
                        }

                        successTaskIds.add(String.valueOf(dingTaskId));
                    }

                    DingdingCommonUtil.updateDingTodo(successTaskIds);
                    logger.info("DingdingServiceHandler--deleteToDo success");
                }
            } catch (Exception var10) {
                logger.info("DingdingServiceHandler--deleteTodoFail:" + var10.getMessage());
                throw new WFMessageServiceException(var10, WFErrorCode.dingdingMsgError(), new Object[]{var10.getMessage()});
            }
        }
    }

    public void sendMessage(MessageContext ctx, MessageInfo message) {
        if (WfConfigurationUtil.isEnabled("dingding")) {
            logger.info("DingdingServiceHandler-- send msg info:" + message);
            MessageServiceUtil.updateToDoMsgContent(this.config, message);
            List<MessageInfo> messages = YunzhijiaToDoUtil.rebuildMessage(message);
            if (MessageUtils.isBlankMessage(messages)) {
                logger.info("DingdingServiceHandler-- messagecontent is blank");
                throw new WFMessageServiceException((Throwable)null, WFErrorCode.sendMsgWithoutContentError(), new Object[0]);
            } else {
                Iterator var4 = messages.iterator();

                while(var4.hasNext()) {
                    MessageInfo messageInfo = (MessageInfo)var4.next();
                    List<Long> userIds = messageInfo.getUserIds();
                    StringBuilder dingUserIds = this.getDingUserIds(userIds);
                    if (StringUtils.isBlank(dingUserIds)) {
                        logger.info("DingdingServiceHandler-- dinguserid is blank");
                        throw new WFMessageServiceException((Throwable)null, WFErrorCode.dingdingMsgError(), new Object[]{"dinguserid is blank:" + userIds});
                    }

                    logger.info("DingdingServiceHandler-- dinguserid:" + dingUserIds);
                    DingdingMessageInfo dingdingMessageInfo = this.buildDingdingMessageInfo(messageInfo, dingUserIds);
                    Map<String, Object> res = MessageServiceHelper.dingdingMessage(dingdingMessageInfo);
                    if (!(Boolean)res.get("result")) {
                        throw new WFMessageServiceException((Throwable)null, WFErrorCode.dingdingMsgError(), new Object[]{"take DingdingHandler has exception " + res.get("description")});
                    }

                    logger.info("DingdingServiceHandler-- send msg success");
                }

            }
        }
    }

    private StringBuilder getDingUserIds(List<Long> userIds) {
        StringBuilder dingUserIds = new StringBuilder();
        List<MessageUser> users = DingdingCommonUtil.getOpenIds(userIds, 2);

        for(int i = 0; i < users.size(); ++i) {
            MessageUser user = (MessageUser)users.get(i);
            if (i == users.size() - 1) {
                dingUserIds.append(user.getOpenId());
            } else {
                dingUserIds.append(user.getOpenId()).append(',');
            }
        }

        return dingUserIds;
    }

    private DingdingMessageInfo buildDingdingMessageInfo(MessageInfo message, StringBuilder dingUserIds) {
        DingdingMessageInfo messageInfo = new DingdingMessageInfo();
        messageInfo.setContent(message.getContent());
        messageInfo.setUserIds(dingUserIds.toString());
        if (StringUtils.isBlank(message.getMobContentUrl())) {
            messageInfo.setLinkMsg(false);
        } else {
            messageInfo.setLinkMsg(true);
            messageInfo.setMsgUrl(message.getMobContentUrl());
            messageInfo.setTitle(message.getTitle());
            messageInfo.setOpenInDing(true);
        }

        messageInfo.setMessageType(DingdingMsgOperateType.CREATE.getNumber());
        return messageInfo;
    }
}

